var express = require('express');
var router = express.Router();
var config = require('../config.json');
var fs = require('fs');
var waterfall = require("async-waterfall");
var path = require("path");
var logger = require('log4js').getLogger();
var EventProxy = require('eventproxy');
var dirs = require('../dirs.js').getDirs();
var xml2js = require('xml2js');
var X2JPaser = new xml2js.Parser();
var builder = new xml2js.Builder();
var platform = require('os').platform();
var workspace_dirs = require('../dirs.js').workspace_dirs;
var cloneGitRepository = require('../gitoper.js').cloneGitRepository;
var removeDir = require('../common/removeDir.js');
var simpleGit = require('simple-git')();
var request = require('request');
var rmdirAllSync = require('../common/tools.js').rmdirAllSync;
var link = require('../target.js').link;
var copy = require('../target.js').copy;
var url = require('url');
var messageAgent = require("../common/message.js");
var uuid = require('uuid');
var decompress = require('decompress');
var decompressUnzip = require('decompress-unzip');
var local_repos = config.local_repo_addr;
var sdp_config = require('../sdp_config.json');
var android_build = require("../build/android_build.js");
var tools = require('../common/tools.js');
var builder_url = url.format(config.app.builder);
var spaces_url = builder_url + '/spaces';
var copy_dir = require('copy-dir');
var zip = require('../common/zip.js');

router.post('/create_workspace', function (req, res, next) {
    var task_id = uuid.v1();
    res.format_json({task_id: task_id}, 200);

    var work_name = req.body.workspace_name;
    var namespace = req.body.namespace;
    var project_name = req.body.project_name;
    var work_id = req.body.work_id;

    var filename = path.join(config.workspace.workspeces_path, config.workspace.space);
    var root = config.workspace.workspeces_path;
    var namespace_dir = path.join(root, namespace);
    var project_dir = path.join(namespace_dir, project_name);
    var full_path = path.join(project_dir, work_name);
    waterfall([
        function (cb) {
            messageAgent.setMessage(task_id, {msg: "创建工作空间目录...", isCompleted: false, err: null});
            fs.access(root, function (err) {
                if (err) {
                    fs.mkdirSync(root);
                }
                fs.access(namespace_dir, function (err) {
                    if (err) {
                        fs.mkdirSync(namespace_dir);
                    }
                    fs.access(project_dir, function (err) {
                        if (err) {
                            fs.mkdirSync(project_dir);
                        }
                        fs.mkdir(full_path, function (err) {
                            if (err) {
                                logger.error(err);
                                messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "工作空间目录创建失败"});
                            } else {
                                dirs.map(function (dir, i) {
                                    fs.mkdirSync(path.join(full_path, dir));
                                });
                                cb(null);
                            }
                        });
                    });
                });
            });
        },
        function (cb) {
            messageAgent.setMessage(task_id, {msg: "修改工作空间配置文件...", isCompleted: false, err: null});
            fs.readFile(filename, 'utf-8', function (err, data) {
                if (err) {
                    logger.error("读取space.xml出错");
                    messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "修改工作空间配置文件失败"});
                } else {
                    cb(null, data);
                }
            });
        },
        function (data, cb) {
            X2JPaser.parseString(data, function (err, result) {
                if (err) {
                    logger.error("修改space.xml出错");
                    messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "修改工作空间配置文件失败"});
                } else {
                    if (typeof(result) == 'undefined' ||
                        typeof(result.workspaces.workspace) == 'undefined') {
                        result = {};
                        result.workspaces = {
                            '$': {
                                name: "workspaces"
                            }
                        };
                        result.workspaces.workspace = [];
                    }
                    var newWork = {
                        '$': {
                            id: work_name,
                            name: work_name,
                            source: 'source',
                            project: project_name,
                            namespace: namespace
                        },
                        repo: [{
                            '$': {
                                name: project_name,
                                branch: "develop"
                            }
                        }]
                    };
                    result.workspaces.workspace.push(newWork);
                    var xmlString = builder.buildObject(result);
                    cb(null, xmlString);
                }
            });
        },
        function (xmlString, cb) {
            fs.writeFile(filename, xmlString, 'utf-8', function (err) {
                if (err) {
                    logger.error("写入space.xml出错");
                    messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "修改工作空间配置文件失败"});
                } else {
                    cb(null);
                }
            });
        },
        //7.新建git库
        function (cb) {
            messageAgent.setMessage(task_id, {msg: "创建git库...", isCompleted: false, err: null});
            var localPath = path.join(config.workspace.workspeces_path,
                namespace, project_name, work_name, workspace_dirs.Source, project_name);
            cloneGitRepository(namespace + '/' + project_name, localPath, function (err, data) {
                if (err) {
                    logger.error(err);
                    messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "创建git库失败"});
                } else {
                    cb(null, data);
                }
            });
        }
    ], function (err, result) {
        if (err) {
            logger.error(err);
            logger.error("create workspace error: unknown reason");
            messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "创建工作空间失败"});
        }
        else {
            messageAgent.setMessage(task_id, {msg: "创建工作空间完成", isCompleted: true, err: null});
        }
    });

});

router.post('/create_master_wkp', function (req, res, next) {
    create_wkp_dirs(req.body, function (err) {
        if (err) {
            return res.format_json(null, 500, "error");
        } else {
            res.format_json(null, 200, "success");
        }
    });
});

router.post('/create_git_repo', function (req, res, next) {
    createGitRepository(req.body, function (err) {
        if (err) {
            return res.format_json(null, 500, "error");
        } else {
            res.format_json(null, 200, "success");
        }
    });
});

router.post('/remove_dir', function (req, res, next) {
    var dir_path = req.body.dir_path;
    try {
        fs.accessSync(dir_path, fs.R_OK);
        rmdirAllSync(dir_path);
        res.format_json(null, 200, "success");
    } catch (e) {
        logger.info(dir_path + ' not exist');
        res.format_json(null, 200, "success");
    }
});

router.post('/workspace/delete', function (req, res, next) {
    var task_id = uuid.v1();
    messageAgent.setMessage(task_id, {msg: "删除工作空间目录...", isCompleted: false, err: null});
    res.format_json({task_id: task_id}, 200);
    delWorkspace(req.body, function (err) {
        if (err) {
            messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "删除工作空间目录创建失败"});
            return false;
        }
        messageAgent.setMessage(task_id, {msg: "工作空间目录删除成功", isCompleted: true, err: null});
        return true;
    });
});
router.delete('/delete_project', function (req, res, next) {
    var data = req.body;
    var workspaces = data.workspaces;
    var namespace = data.namespace;
    var project_name = data.project_name;
    var ep = new EventProxy();
    ep.fail(function (err) {
        logger.error(err);
        res.format_json(null, 500, "delete project error");
    });
    ep.after('spaceXml_update', workspaces.length, function () {
        var project_dir_in_workspaces = path.join(config.workspace.workspeces_path, namespace, project_name);
        var project_dir_in_master_workspaces = path.join(config.master_workspaces, namespace, project_name);
        try {
            fs.accessSync(project_dir_in_workspaces, fs.R_OK);
            rmdirAllSync(project_dir_in_workspaces);
        } catch (e) {
            logger.info(project_dir_in_workspaces + ' not exist');
        }
        ;
        try {
            fs.accessSync(project_dir_in_master_workspaces, fs.R_OK);
            rmdirAllSync(project_dir_in_master_workspaces);
            res.format_json(null, 200, "success");
        } catch (e) {
            logger.info(project_dir_in_master_workspaces + ' not exist');
            res.format_json(null, 200, "success");
        }
    });
    ep.on("something_wrong", function () {
        logger.error(err);
        res.format_json(null, 500, "delete project error");
    });
    var spaceXML = path.join(config.workspace.workspeces_path, config.workspace.space);
    //先修改space.xml
    workspaces.forEach(function (workspace) {
        fs.readFile(spaceXML, 'utf-8', function (err, data) {
            if (err) {
                logger.error('read space.xml failed');
                ep.emit('something_wrong');
            }
            X2JPaser.parseString(data, function (err, result) {
                var array = result.workspaces.workspace;
                if (typeof(result.workspaces.workspace) == 'undefined') {
                    logger.error("space.xml不存在");
                    ep.emit('something_wrong');
                } else {
                    for (var i = 0; i < array.length; i++) {
                        var work = array[i];
                        if (work.$.id == workspace.work_name) {
                            array.splice(i, 1);
                        }
                    }
                    if (array.length == 0) {
                        result.workspaces = {
                            '$': {
                                name: "workspaces",
                            }
                        };
                    } else {
                        result.workspaces.workspace = array;
                    }
                    var xmlString = builder.buildObject(result);
                    fs.writeFile(spaceXML, xmlString, 'utf-8', function (err) {
                        if (err) {
                            logger.error("space.xml重写失败");
                            ep.emit('something_wrong');
                        }
                        logger.info('workspace: "' + workspace.work_name + '" deleted!');
                        ep.emit('spaceXml_update');
                    });
                }
            });
        })
    });

});

router.post('/local_repo/download', function (req, res, next) {
    var task_id = uuid.v1();
    messageAgent.setMessage(task_id, {
        msg: "开始下载" + req.body.fileName + "_" + req.body.version,
        isCompleted: false,
        err: null
    });
    res.format_json({task_id: task_id}, 200);
    downloadGoods(req.body.version, req.body.fileName, req.body.type, function (err, data) {
        if (err) {
            messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "下载失败"});
            return false;
        }
        messageAgent.setMessage(task_id, {msg: "下载成功", isCompleted: true, err: null});
        return true;
    });
});

router.post('/local_repo/update', function (req, res, next) {
    var task_id = uuid.v1();
    messageAgent.setMessage(task_id, {
        msg: "开始更新" + req.body.fileName + "_" + req.body.version,
        isCompleted: false,
        err: null
    });
    res.format_json({task_id: task_id}, 200);
    downloadGoods(req.body.version, req.body.fileName, req.body.type, function (err, data) {
        if (err) {
            messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "更新失败"});
            return false;
        } else {
            messageAgent.setMessage(task_id, {msg: "更新成功", isCompleted: true, err: null});
            return true;
        }

    });
});

router.post('/workspace/dependencies/update', function (req, res, next) {
    var data = req.body;
    switch (platform) {
        case 'linux' :
            link(data, false, function (err) {
                if (err) {
                    logger.error(err);
                    res.format_json({}, 500, err);
                } else {
                    res.format_json({}, 200);
                }
            });
            break;
        case 'darwin' :
            link(data, false, function (err) {
                if (err) {
                    logger.error(err);
                    res.format_json({}, 500, err);
                } else {
                    res.format_json({}, 200);
                }
            });
            break;
        case 'win32' :
            link(data, true, function (err) {
                if (err) {
                    logger.error(err);
                    res.format_json({}, 500, err);
                } else {
                    res.format_json({}, 200);
                }
            });
            break;
        default :
            res.format_json({}, 500, "不支持的操作系统类型");
        //copy(data, function (err) {
        //    if (err) {
        //        logger.error(err);
        //        res.format_json({}, 500,err);
        //    } else {
        //        res.format_json({}, 200);
        //    }
        //})
    }
});

router.post('/appAndroidBuild', function (req, res, next) {
    var project_info = req.body.project_info;
    var cert_info = req.body.cert_info;
    var projects = req.body.projects;

    var project_location = "";

    var temp_dir = null;
    try {
        temp_dir = tools.createTempDirSync();
    } catch (e) {
        return ep.throw('创建临时目录失败' + (e.message ? e.message : e));
    }

    var ep = new EventProxy();
    ep.fail(function (err) {
        res.format_json(null, 500, err);
    });

    android_build.prepareMasterWorkspace(project_info, function (err, data) {
        if (err) {
            return ep.throw('error occurs when prepare master workspace.');
        }
        ep.emit('master_workspace_ready');
    });


    ep.on('master_workspace_ready', getPluginsInfo());

    function getPluginsInfo() {
        //获取插件信息 检查插件状态
        var project = projects[0];
        project_location = config.master_workspaces + path.sep + project.location;
        var plugin_conf_location = path.join(project_location, "carrier", "carrier.config");
        try {
            fs.accessSync(plugin_conf_location, fs.R_OK);
            var plugin_str = fs.readFileSync(plugin_conf_location, 'utf-8');
            RN_plugins = typeof(JSON.parse(plugin_str).target) == 'undefined' ? [] : JSON.parse(plugin_str).target;

        } catch (e) {
            return ep.throw(e);
        }
        var plugins = {
            'RN': RN_plugins
        };
        var dependencies = project_info.dependencies;
        ep.after('RN_plugin_found', RN_plugins.length, function () {
            getSpace();
        });
        for (var i = 0; i < RN_plugins.length; i++) {
            var plugin = RN_plugins[i];
            var index = _.findIndex(dependencies, function (dep) {
                return dep.name == plugin.name && dep.goods_version == plugin.version;
            });
            if (index < 0 || dependencies[index].status == 0) {
                logger.info('plugin error: ' + plugin.name + ' not ordered.');
                return ep.throw('plugin error: ' + plugin.name + ' not ordered.');
                //return tryCallback(callback, 'plugin error: ' + plugin.name + ' not ordered.');
            } else {
                if (dependencies[index].status == 1) {
                    //插件未缓存，下载插件
                    logger.info(plugin.name + 'version ' + plugin.version + ' not in local_repo, downing...');
                    downloadGoods(plugin.version, plugin.name, "app_plugin", function (err, data) {
                        if (err) {
                            logger.error("下载文件失败：" + err);
                            return ep.throw('plugin error: ' + plugin.name + ' download failed.');
                        } else {
                            //todo::下载后应该修改localRepo 这里暂时先不更新
                            plugin['location'] = path.join(local_repo_path, plugin.name + '_' + plugin.version + '.zip');
                            ep.emit('RN_plugin_found');
                            logger.info("下载文件成功")
                        }

                    });
                } else {
                    plugin['location'] = path.join(local_repo_path, plugin.name + '_' + plugin.version + '.zip');
                    ep.emit('RN_plugin_found');
                }
            }
        }
    }

    function getSpace() {
        request.post(spaces_url).on('response', function (response) {
            tools.pareseResponseJSON(response, function (err, response) {
                if (err || 200 != response.statusCode) {
                    return ep.throw('get sapce from ' + spaces_url + ' faild.');
                } else {
                    spaceID = response.body.spaceID;
                    if (!spaceID) {
                        return ep.throw('get sapce from ' + spaces_url + ' faild.');
                    }
                    ep.emit('space_ready');
                }
            })
        }).on('error', function (err) {
            return ep.throw('get sapce from ' + spaces_url + ' faild.');
        });
    }

    ep.on('space_ready', function () {
        logger.info('space_ready');
        var upload_temp = null;
        try {
            upload_temp = tools.createTempDirSync();
        } catch (e) {
            return ep.throw('创建临时目录失败' + (e.message ? e.message : e));
        }
        var location = project_location;
        var fileName = 'project.zip';
        var project_file_path = path.join(upload_temp, fileName);
        //收集插件，放在temp_dir - project - plugins - RN -  plugin_name
        var plugin_dir = path.join(temp_dir, 'plugins');
        var RN_plugin = path.join(plugin_dir, 'RN');

        fs.mkdirSync(plugin_dir);
        fs.mkdirSync(RN_plugin);
        if (RN_plugins && RN_plugins.length) {
            ep.after('plugin_ready', RN_plugins.length, function () {
                copy_dir.sync(location, temp_dir);
                zip.zip(temp_dir, project_file_path, function (err, data) {
                    if (err) {
                        return ep.throw('zip file faild.');
                    }
                    var url = spaces_url + "/" + spaceID + '/input/' + fileName;
                    tools.upload(project_file_path, url, ep.done('project_uploaded'));
                });
            });
            for (var it = 0; it < RN_plugins.length; it++) {
                //RN_plugins[it]解压到RN，再次解压后删除path.join(RN_plugin,'nectar_plugin.zip')
                (function (it) {
                    ep.on("plugin_" + (it) + "_prepared", function () {
                        zip.unzip(RN_plugins[it].location, RN_plugin, function (err) {
                            if (err) {
                                logger.error('unzip ' + RN_plugins[it].location + 'to ' + RN_plugin + ' error');
                                return ep.throw('get plugin :' + RN_plugins[it].name + " failed");
                            }
                            zip.unzip(path.join(RN_plugin, 'nectar_plugin.zip'), RN_plugin, function (err) {
                                if (err) {
                                    logger.error('unzip ' + RN_plugins[it].location + 'to ' + RN_plugin + ' error');
                                    return ep.throw('get plugin :' + RN_plugins[it].name + " failed");
                                }
                                fs.unlinkSync(path.join(RN_plugin, 'nectar_plugin.zip'));
                                ep.emit("plugin_" + (it + 1) + "_prepared");
                                ep.emit("plugin_ready");
                            });

                        })

                    });
                })(it);
            }
            ep.emit("plugin_" + 0 + "_prepared");
        } else {
            copy_dir.sync(location, temp_dir);
            zip.zip(temp_dir, project_file_path, function (err, data) {
                if (err) {
                    return ep.throw('zip file faild.');
                }
                var url = spaces_url + "/" + spaceID + '/input/' + fileName;
                tools.upload(project_file_path, url, ep.done('project_uploaded'));
            });

        }

    });

    ep.on('project_uploaded', function () {
        logger.info('project_uploaded');
        ep.on('cert_find', function () {

            var files = cert_info.files;
            var keystoreFile = files.keystoreFile;

            var url = spaces_url + "/" + spaceID + '/input/' + keystoreFile.file_name;
            tools.upload(keystoreFile.file_path, url, ep.done('cert_uploaded'));
        });

        if (cert_info == null) {
            logger.info(product_config.name + " use default certs");
            ep.emit('cert_uploaded')
        }  else {
            ep.emit('cert_find');
        }

        ep.after('cert_ready', function (results) {
            if (_.indexOf(results, false) > -1) {
                return ep.throw('ready cert failed.');
            }
            ep.emit('cert_all_ready');
        });
    });

    ep.on('cert_uploaded', readyJSON);

    function readyJSON() {

        logger.info('cert_uploaded');
        var data = {
            "android": {
                "isBuild": "true",
                "isDefault": "true",
                "keystoreFilename": "project.keystore",
                "keystorePassword": "123"
            },
            "ios": {
                "isDefault": "true",
                "isBuild": "false",
                "p12Filename": "project.p12",
                "p12Password": "P@ssw0rd",
                "ppID": "nectardefault",
                "ppFilename": "project.mobileprovision"
            }
        };
        if (cert) {
            data = {
                "android": {
                    "isBuild": "true",
                    "isDefault": "false",
                    "keystoreFilename": cert.files.keystoreFile.file_name,
                    "keystorePassword": cert.extend_info.KeyStoreSecret
                },
                "ios": {
                    "isDefault": "true",
                    "isBuild": "false",
                    "p12Filename": "project.p12",
                    "p12Password": "P@ssw0rd",
                    "ppID": "nectardefault",
                    "ppFilename": "project.mobileprovision"
                }
            };
        }
        var json_file_path = path.join(temp_dir, 'sign_info.json');
        fs.writeFile(json_file_path, JSON.stringify(data), function (err) {
            if (err) {
                return ep.throw(err);
            } else {
                ep.emit('json_ready', json_file_path);
            }
        });


        ep.on('json_ready', function (json_file_path) {

            logger.info('json_ready');

            var fileName = 'sign_info.json'
            var url = spaces_url + "/" + spaceID + '/input/' + fileName;
            tools.upload(json_file_path, url, ep.done('json_uploaded'));

        })
        ep.on('json_uploaded', function () {
            logger.info('all_uploaded');
            var begin_url = builder_url + '/execute?task=buildnative&space=' + spaceID + '&action=begin';
            request.get(begin_url).on('response', function (response) {
                tools.pareseResponseJSON(response, function (err, response) {
                    if (err || 200 != response.statusCode) {
                        setBuildState(build, 'error');
                        return ep.throw(err);
                    } else {
                        res.format_json({spaceID:spaceID},200,null);
                    }
                });
            })
        })

    }

});

router.get('/message/:task_id', messageAgent.handleMessage);


function create_wkp_dirs(project_info, callback) {
    var ep = new EventProxy();
    ep.fail(callback);
    ep.on("master_workspace_created", callback);

    var dirs = require('../dirs.js').getDirs();
    var root = config.master_workspaces;
    var namespace_dir = path.join(root, project_info.namespace);
    var full_path = path.join(namespace_dir, project_info.name);
    fs.access(root, function (err) {
        if (err) {
            fs.mkdirSync(root);
        }
        fs.access(namespace_dir, function (err) {
            if (err) {
                fs.mkdirSync(namespace_dir);
            }
            try {
                fs.accessSync(full_path, fs.R_OK);
                removeDir.remove(full_path, function (err) {
                    if (err) {
                        logger.error("删除原目录失败");
                        return callback("删除原目录失败");
                    }
                    fs.mkdirSync(full_path);
                    dirs.map(function (dir, i) {
                        fs.mkdirSync(path.join(full_path, dir));
                    });
                    logger.info("master_workspace 目录创建成功");
                    ep.emit("master_workspace_created");
                });

            } catch (e) {
                fs.mkdirSync(full_path);
                dirs.map(function (dir, i) {
                    fs.mkdirSync(path.join(full_path, dir));
                });
                logger.info("master_workspace 目录创建成功");
                ep.emit("master_workspace_created");
            }
        })
    });
}

function createGitRepository(project, call_back) {

    var workspace_dirs = require('../dirs.js').workspace_dirs;
    var repoPath = config.workspace.gitolite.repo_pre + project.namespace + '/' + project.name;
    var localPath = path.join(config.master_workspaces, project.namespace,
        project.name, workspace_dirs.Source, project.name);
    var ignore_path = path.join(localPath, ".gitignore");
    var git_server = "http://" + config.git_server.host + ":" + config.git_server.port + "/api/git/create";

    waterfall([
        //1.调用git-server创建git库
        function (cb) {
            request.post({
                url: git_server,
                form: {project_name: project.namespace + '/' + project.name}
            }, function (err, req) {
                if (err) {
                    logger.error(err);
                    logger.error("调用git服务出错");
                    return call_back(err);
                }
                if (req.body.code == "500") {
                    logger.error(res.msg);
                    return call_back(res.msg);
                }
                logger.info("git服务创建git库成功");
                cb(null);
            });
        },
        //2.clone项目
        function (cb) {
            fs.exists(localPath, function (exists) {
                if (exists) {
                    removeDir.remove(localPath, function (err) {
                        if (err) {
                            logger.info("删除原目录失败");
                        }
                        simpleGit.clone(repoPath, localPath, function (err, data) {
                            if (err) {
                                logger.error(err);
                                logger.error("clone项目失败");
                                return call_back(err);
                            }
                            logger.info("clone项目成功");
                            cb(null);
                        });
                    });
                } else {
                    simpleGit.clone(repoPath, localPath, function (err, data) {
                        if (err) {
                            logger.error(err);
                            logger.error("clone项目失败");
                            return call_back(err);
                        }
                        logger.info("clone项目成功");
                        cb(null);
                    });
                }
            });
        },
        function (cb) {
            fs.writeFile(ignore_path, "*/jmx/*\r\n*.class", 'utf-8', function (err) {
                if (err) {
                    logger.error(err);
                    logger.error("创建.gitignore文件出错");
                    return call_back(err);
                }
                logger.info("创建.gitignore文件成功");
                cb(null);
            });
        },
        function (cb) {
            require('simple-git')(localPath)
                .add('./.gitignore')
                .commit("first commit!")
                .push('origin', 'master', function (err, data) {
                    if (err) {
                        logger.error(err);
                        logger.error("推送.gitignore出错");
                        return call_back(err);
                    }
                    logger.info("推送.gitignore成功");
                }).checkoutLocalBranch('develop', function (err, result) {
                if (err) {
                    logger.error(err);
                    logger.error("切换develop失败");
                    return call_back(err);
                }
                logger.info("切换develop成功");
            }).push('origin', 'develop', function (err, data) {
                if (err) {
                    logger.error(err);
                    logger.error("推送develop分支出错");
                    return call_back(err);
                }
                logger.info("推送develop成功");
            }).checkout('master', function (err, result) {
                if (err) {
                    logger.error(err);
                    logger.error("切回master失败");
                    return call_back(err);
                }
                logger.info("切回master成功");
                cb(null);
            });
        }
    ], function (err, result) {
        if (err) {
            logger.error(err);
            return call_back("未知的异常，创建git库失败");
        }
        call_back(null, "done");
    });
}

var delWorkspace = function (workspace_info, call_back) {
    var workspace_namespace = workspace_info.namespace;
    var workspace_project_name = workspace_info.project_name;
    var workspace_name = workspace_info.work_name;
    var root = config.workspace.workspeces_path;
    var namespace_path = path.join(root, workspace_namespace);
    var project_dir = path.join(namespace_path, workspace_project_name);

    var filename = path.join(config.workspace.workspeces_path, config.workspace.space);
    waterfall([
        //1.获取工作空间信息
        function (cb) {
            //    WorkspaceProxy.getWorkspaceById(workspace_id, function (err, workspace) {
            //        if (err) {
            //            logger.error(err);
            //            return call_back(err);
            //        }
            //        logger.info("获取工作空间信息成功");
            //        cb(null, workspace);
            //    });
            //},
            ////2.删除目录，读取space.xml
            //function (workspace, cb) {
            var workspace_path = path.join(project_dir, workspace_name);
            removeDir.remove(workspace_path, function (err) {
                if (err) {
                    logger.error(err);
                    return call_back(err);
                }
                logger.info("删除目录成功");
                //读取space.xml
                fs.readFile(filename, 'utf-8', function (err, data) {
                    if (err) {
                        logger.error(err);
                        return call_back(err);
                    }
                    logger.info("读取space.xml成功");
                    cb(null, data);
                });
            });
        },
        //3.修改space.xml
        function (data, cb) {
            X2JPaser.parseString(data, function (err, result) {
                var array = result.workspaces.workspace;
                if (typeof(result.workspaces.workspace) == 'undefined') {
                    logger.error("space.xml不存在");
                    return call_back(err);
                } else {
                    for (var i = 0; i < array.length; i++) {
                        var work = array[i];
                        if (work.$.id == workspace_name) {
                            array.splice(i, 1);
                        }
                    }
                    if (array.length == 0) {
                        result.workspaces = {
                            '$': {
                                name: "workspaces"
                            }
                        };
                    } else {
                        result.workspaces.workspace = array;
                    }
                    var xmlString = builder.buildObject(result);
                    logger.info("修改space.xml成功");
                    cb(null, xmlString);
                }
            });
        },
        //4.写入space.xml 删除数据库数据
        function (xmlString, cb) {
            fs.writeFile(filename, xmlString, 'utf-8', function (err) {
                if (err) {
                    logger.error(err);
                    return call_back(err);
                }
                logger.info("写入space.xml成功");
                cb(null);
                //WorkspaceProxy.deleteWorkspace(workspace_id, function (err) {
                //    if (err) {
                //        logger.error(err);
                //        return call_back(err);
                //    }
                //    logger.info("删除数据库数据成功");
                //    cb(null)
                //});
            });
        }
    ], function (err) {
        if (err) {
            logger.error(err);
            return call_back(err);
        }
        return call_back(null, "success");
    });
};

function downloadGoods(version, fileName, type, callback) {
    request(config.store.store_private + '/store/query_download?name=' + fileName + '_' + version, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var body = JSON.parse(body);
            if (body && body.data && body.data.url) {
                logger.info("get down_load_uri:" + body.data.url);
                request.get(body.data.url).on('response', function (response) {
                    if (response.statusCode != 200) {
                        exe_callback("未知的错误，下载失败", null, callback);
                    } else {
                        logger.info("downloading...");
                        var dependency_dir = path.join(local_repos, fileName + "_" + version);
                        var zip_path = path.join(local_repos, fileName + "_" + version + ".zip");
                        var writeStream = fs.createWriteStream(zip_path);
                        response.pipe(writeStream);
                        writeStream.on('close', function () {
                            //依赖下载后 先解压到fileName目录下，如果是mk 需要读取目录后再次解压
                            //依赖下载为zip文件后，根据不同类型解压
                            var epc = new EventProxy();
                            epc.after("file_existed", 1, function () {
                                if (type == sdp_config.goods_type.core_node) {
                                    fs.createReadStream(zip_path).pipe(fs.createWriteStream(path.join(dependency_dir, fileName + "_" + version + ".zip")));
                                    logger.info("download success");
                                    exe_callback(null, null, callback);
                                } else {
                                    decompress(zip_path, dependency_dir, {
                                        plugins: [
                                            decompressUnzip()
                                        ]
                                    }).then(function (data) {
                                        if (data.length == 0) {
                                            logger.error("解压文件出错");
                                        } else {

                                            //根据不同的类型对商品进行处理
                                            if (type == sdp_config.goods_type.MK || type == "app_plugin") {
                                                logger.info("unzip_target");
                                                fs.readdir(dependency_dir, function (err, array) {
                                                    if (err) {
                                                        return exe_callback(err, data, callback);
                                                    }

                                                    array.map(function (filename, i) {
                                                        //解压文件
                                                        decompress(path.join(dependency_dir, filename), dependency_dir, {
                                                            plugins: [
                                                                decompressUnzip()
                                                            ]
                                                        }).then(function (data) {
                                                            if (data.length == 0) {
                                                                exe_callback("解压文件出错", data, callback);
                                                                return false;
                                                            } else {
                                                                fs.unlink(path.join(dependency_dir, filename), function (err, data) {
                                                                    if (err) {
                                                                        return exe_callback("删除临时文件出错", data, callback);
                                                                    }
                                                                    logger.info("解压完成");
                                                                    logger.info("download success");
                                                                    exe_callback(null, data, callback);
                                                                    //epc.emit("download_success");
                                                                });
                                                            }
                                                        });
                                                    });
                                                });
                                            } else {
                                                //解压文件
                                                logger.info("download success");
                                                exe_callback(null, data, callback);
                                            }
                                        }
                                    });
                                }
                            })
                            fs.exists(dependency_dir, function (exists) {
                                if (!exists) {
                                    fs.mkdir(dependency_dir, function (err) {
                                        if (err) {
                                            return exe_callback(err, data, callback);
                                        }
                                        epc.emit("file_existed");
                                    });
                                } else {
                                    removeDir.remove(dependency_dir, function (err) {
                                        if (err) {
                                            return exe_callback(err, null, callback);
                                        }
                                        fs.mkdir(dependency_dir, function (err) {
                                            if (err) {
                                                return exe_callback(err, null, callback);
                                            }
                                            epc.emit("file_existed");

                                        });

                                    });
                                }
                            });
                        });
                    }
                }).on('error', function (err) {
                    exe_callback(err, null, callback);
                });
            } else {
                exe_callback("未知的错误，无法获取下载链接", null, callback);
            }
        } else {
            exe_callback(error, null, callback);
        }
    });
}

function exe_callback(err, data, callback) {
    if (callback && typeof callback === 'function') {
        callback(err, data);
    }
}

module.exports = router;
